using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;

namespace IQIGame.Onigao.GamePlay
{
    public class CFSMState_Level_Logic_Monster_Patrol : CFSMState<IQIGame.Onigao.Logic.LevelEntity, CFSMLevel_Logic_MonsterData>
    {
        private LgEntityPatrolComponent _patrolCom;
        public override void OnInit()
        {

        }

        public override void OnEnter(int prevStateId)
        {
            EntityParamPatrolPath patrolParam = null;
            if (entity.entityConfig.paramMap.TryGetValue(EntityDynamicParamType.PatrolPath, out var dynParam))
            {
                patrolParam = dynParam as EntityParamPatrolPath;
            }
            if (patrolParam != null && patrolParam.patrolPath != null && patrolParam.patrolPath.Count > 0)
            {
                //巡逻状态只管理巡逻组件的启停，但不会彻底移除它，只有在追击时才会移除，以保证警戒恢复巡逻的正确性。
                _patrolCom = entity.GetComponent<LgEntityPatrolComponent>();
                if (_patrolCom == null)
                {
                    _patrolCom = entity.AddComponent<LgEntityPatrolComponent>();
                    //如果是从追击状态切换过来的，则指定一个追击起始位置作为巡逻的初始位置，但目前只有不巡逻的怪按照这个位置返回巡逻点，有巡逻路径的怪会寻找最近的巡逻点
                    _patrolCom.StartPatrol();
                }
                else
                {
                    _patrolCom.SetActive(true);
                }
            }
            else if (data.dirBeforeChase != null)
            {
                Vector3Logic euler = Vector3Logic.DirectionToEulerXy(data.dirBeforeChase.Value);
                int rotationY = (int)System.Math.Round(euler.y);
                entity.SetRotationY(rotationY, true);
            }

            data.dirBeforeChase = null;
        }

        public override void OnUpdate(float deltaTime)
        {

        }

        public override void OnExit()
        {
            //离开时不移除组件，在追击时移除
            _patrolCom?.SetActive(false);
            _patrolCom = null;
        }

        public override void OnReset()
        {
            base.OnReset();
        }
    }
}
